package com.ndp.fb.walle.business.impl;

import com.alibaba.dubbo.config.annotation.Reference;
import com.ndp.fb.rdb.api.AdPublishConditionRdbService;
import com.ndp.fb.rdb.api.RuleSettingsRdbService;
import com.ndp.fb.rdb.model.EntrustAccountExt;
import com.ndp.fb.rdb.model.RuleSettings;
import com.ndp.fb.rdb.model.adpublishcondition.AdPublishConditionResult;
import com.ndp.fb.util.ListUtil;
import com.ndp.fb.walle.business.EntrustAccountService;
import com.ndp.fb.walle.business.RuleSettingsService;
import com.ndp.fb.walle.model.vo.rulesetting.param.SetingsFbAccount;
import com.ndp.fb.walle.model.vo.rulesetting.param.SettingsVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by hunk.qin on 2015/9/15.
 */
@Component
public class RuleSettingsServiceImpl implements RuleSettingsService {

    @Reference
    private RuleSettingsRdbService ruleSettingsRdbService;

    @Reference
    private AdPublishConditionRdbService adPublishConditionRdbService;

    @Autowired
    EntrustAccountService entrustAccountService;


    @Override
    public void saveSettings(List<SettingsVo> settingsVos,String userid) {
        List<RuleSettings> ruleSettingses=new ArrayList<>();
        for (SettingsVo settingsVo : settingsVos) {
            RuleSettings ruleSettings=new RuleSettings();
            ruleSettings.setUserId(userid);
            ruleSettings.setLossLimit(settingsVo.getLossLimits());
            ruleSettings.setFbConnectionObjectId(settingsVo.getConnObjId());
            ruleSettings.setKeyWord(settingsVo.getKeyWord());
            ruleSettings.setPlatform(settingsVo.getPlatform());
            String fbaccouns="";
            for ( SetingsFbAccount fbaccount : settingsVo.getFbAccounts()) {
                fbaccouns+=fbaccount.getFbAccountId()+",";
            }
            if(fbaccouns.length()>1) fbaccouns=fbaccouns.substring(0,fbaccouns.length()-1);
            ruleSettings.setFbAccounts(fbaccouns);
            ruleSettingses.add(ruleSettings);
        }
         ruleSettingsRdbService.deleteByUserId(userid  );
         ruleSettingsRdbService.saveSetting(ruleSettingses);
    }

    @Override
    public List<SettingsVo> getSettingsVoByUserId(String userId, Long orgId) {
        List<AdPublishConditionResult> onAdps = getOnApp(adPublishConditionRdbService.
                findAdPublishConditionWithPager(userId, "", orgId));
        List<RuleSettings> ruleSettingses = ruleSettingsRdbService.getRuleSettingsByUserId(userId);

        if(ListUtil.isEmpty(ruleSettingses)){//如果用户没有任何应用的设置，则把所有有权限并且投放控制是 on 的应用都初始化到setting里面去
            ruleSettingses=new ArrayList<>();
            for (AdPublishConditionResult adp : onAdps) {
                ruleSettingses.add(buildSettingByAdp(adp,userId));
            }
            ruleSettingsRdbService.saveSetting(ruleSettingses);
        }

        //开始比较哪些是已经选择的
        List<SettingsVo> settingsVoList=new ArrayList<>();
        for (AdPublishConditionResult onAdp : onAdps) {
            settingsVoList.add(buildSettingsVo(onAdp,ruleSettingses,userId));
        }
        return settingsVoList;
    }

    private List<AdPublishConditionResult> getOnApp(List<AdPublishConditionResult> adps){
        List<AdPublishConditionResult> onAdps=new ArrayList<>();
        for (AdPublishConditionResult adp : adps) {
            if(adp.getStatus()==1){
                onAdps.add(adp);
            }
        }
        return onAdps;
    }

    private RuleSettings buildSettingByAdp(AdPublishConditionResult adp,String userid){
        RuleSettings ruleSettings=new RuleSettings();
        ruleSettings.setUserId(userid);
        ruleSettings.setLossLimit(100);
        ruleSettings.setFbConnectionObjectId(adp.getConnObjId());
        ruleSettings.setKeyWord("");
        ruleSettings.setPlatform(adp.getProdCfgName());
        List<EntrustAccountExt> entrustAccounts = entrustAccountService.
                findEntrustAccountsByfbConnectionObjectIdAndUserId(adp.getConnObjId(), userid);
        String fbaccouns="";
        for (EntrustAccountExt entrustAccount : entrustAccounts) {
            fbaccouns+=(entrustAccount.getFbAccountId()+",");
        }
        ruleSettings.setFbAccounts(fbaccouns.substring(0,fbaccouns.length()-1));

        return ruleSettings;
    }

    private SettingsVo buildSettingsVo(AdPublishConditionResult adp,List<RuleSettings> ruleSettingses,String userid){
        SettingsVo settingsVo=new SettingsVo();
        RuleSettings ruleSetings=null;
        for (RuleSettings ruleSettingse : ruleSettingses) {
            if(adp.getConnObjId().equals(ruleSettingse.getFbConnectionObjectId()) && adp.getProdCfgName().equals(ruleSettingse.getPlatform())){
                ruleSetings=ruleSettingse;
            }
        }
        if(ruleSetings==null){
            settingsVo.setKeyWord("");
            settingsVo.setLossLimits(100);
            settingsVo.setIsSelect(false);
            settingsVo.setFbAccounts(getFbAccountVoList(adp, userid,null));
        }else{
            settingsVo.setKeyWord(ruleSetings.getKeyWord());
            settingsVo.setLossLimits(ruleSetings.getLossLimit());
            settingsVo.setIsSelect(true);
            settingsVo.setFbAccounts(getFbAccountVoList(adp, userid, CollectionUtils.arrayToList(ruleSetings.getFbAccounts().split(","))));
        }
        settingsVo.setPlatform(adp.getProdCfgName());
        settingsVo.setConnObjName(adp.getConnObjName());
        settingsVo.setConnObjId(adp.getConnObjId());
        return settingsVo;
    }

    private List<SetingsFbAccount> getFbAccountVoList(AdPublishConditionResult adp, String userid,List<String> fbaccounts) {
        List<EntrustAccountExt> entrustAccounts = entrustAccountService.
                findEntrustAccountsByfbConnectionObjectIdAndUserId(adp.getConnObjId(), userid);
        List<SetingsFbAccount> fbAccounts=new ArrayList<>();
        for (EntrustAccountExt accountExt : entrustAccounts) {
            SetingsFbAccount setingsFbAccount=new SetingsFbAccount();
            setingsFbAccount.setFbAccountname(accountExt.getName());
            setingsFbAccount.setFbAccountId(String.valueOf(accountExt.getFbAccountId()));
            if(fbaccounts==null){
                setingsFbAccount.setIsSelect(true);
            }
            else{
                if(fbaccounts.contains(String.valueOf(accountExt.getFbAccountId()))){
                    setingsFbAccount.setIsSelect(true);
                }else{
                    setingsFbAccount.setIsSelect(false);
                }
            }

            fbAccounts.add(setingsFbAccount);
        }

        return fbAccounts;
    }
}

